import {request} from "../../utils/request";
import config from "../../utils/config";
import {formatTime} from "../../utils/util"

const app = getApp();
Page({
    data: {
        picUrl: config.picUrl,
        url: config.url,
        formData: {album_id: 1},
        header: {'contentType': 'application/x-www-form-urlencoded;charset=utf-8'},
        custom: wx.getMenuButtonBoundingClientRect(),
        user: wx.getStorageSync('userInfo'),
        title: '发布',
        sku: [], //所有的sku属性,用作页面列表渲染
        id: null, //以下都是商品的属性
        name: '',
        img: '', //商品列表页图片
        brand_id: null, //商家id
        type: '', //商品类型 1-盒装；2-独家限定；3-城市限定；4-桌游；5-周边（服装道具）
        is_new: '', //是否新品
        scrbing_price: '', //原价
        discount_price: '', //折扣价
        delivery: '', //发货方式、配送方式
        free_freight: 1, //是否包邮
        freight: '', //运费
        is_presell: 2, //是否是预售
        sales_date: '', //预售截止日期
        material: '', //售后资料
        content: '', //商品文字介绍
        bannerList: [], //轮播图列表
        skus: [], //商品所有的sku
        old: null, //商品新旧程度
        previous_box: 1, //是否有原盒 1:-有，2-无
        clue_card: 1, //线索卡是否缺失：1-无缺失；2-有缺失
        play_status: 1, //人物剧本状态：1-完好；2-破损；3-缺失
        population: 0,//人数
        male: '', //男性人数
        female: '', //女性人数
        gender_restrict: 2, //是否限制男女，1-限制；2-不限制
        cross_dressing: 1, //是否可反转：1-不可反转；2-可反转
        words_num: '', //阅读体量 万为单位
        duration: '', //演绎时长 小时为单位
        host_difficulty: 0, //主持难度
        deduction_difficulty: 0, //演绎难度
        prop: '', //附赠道具
        buy_info: '',
        status: 2,
        visible: false,
        lang: 'zh_CN',
    },
    onLoad(options) {
        this.getSkus()
        if ('id' in options) {
            this.setData({id: options.id})
            this.getData()
        } else {
            var {type, is_new} = options
            this.setData({type, is_new, brand_id: this.data.user.id})
            if (options.is_new == 2) {
                this.setData({title: this.data.title + '闲置'})
            }
            var txt = ''
            switch (options.type) {
                case "1":
                    txt = '盒装'
                    break;
                case "2":
                    txt = '城市独家'
                    break;
                case "3":
                    txt = '城市限定'
                    break;
                case "4":
                    txt = '桌游'
                    break;
                case "5":
                    txt = '周边'
                    break;
            }
            this.setData({title: this.data.title + txt})
        }
    },
    uploadImg() {
        this.upload(1, res => {
            if (res.code != 200) {
                wx.showToast({title: res.msg, icon: 'none'})
                return false
            }
            this.setData({img: res.data.src})
        })
    },
    uploadBanner() {
        this.upload(9 - this.data.bannerList.length, res => {
            var bannerList = this.data.bannerList
            bannerList.push(res.data.src)
            this.setData({bannerList})
        })
    },
    uploadBuyInfo() {
        this.upload(1, res => {
            if (res.code != 200) {
                wx.showToast({title: res.msg, icon: 'none'})
                return false
            }
            this.setData({buy_info: res.data.src})
        })
    },
    delImg() {
        this.setData({img: ''})
    },
    delBanner(e) {
        var index = e.currentTarget.dataset.index,
            bannerList = this.data.bannerList
        var res = bannerList.splice(index, 1)
        this.setData({bannerList})
    },
    delBuyInfo() {
        this.setData({buy_info: ''})
    },
    upload(count, callback) {
        wx.showLoading()
        wx.chooseImage({
            count: count,
            sizeType: ['compressed', 'original'],
            success: res => {
                for (let v of res.tempFiles) {
                    wx.uploadFile({
                        url: this.data.url + '/system/api/uploadImage',
                        filePath: v.path,
                        name: 'file',
                        formData: this.data.formData,
                        success: res => {
                            wx.hideLoading()
                            callback(JSON.parse(res.data))
                        }
                    })
                }
            },
            fail: err => {
                wx.hideLoading()
            }
        })

    },
    getSkus() {
        request({url: "/miniprogram/system/getFilterData"}).then(res => {
            this.setData({sku: res.data})
        })
    },
    chooseSku(e) {
        var sku = this.data.skus,
            {type, value, pid} = e.currentTarget.dataset
        value = parseInt(value)
        if (sku.indexOf(value) > -1) {
            sku = sku.filter(item => item != value)
            this.setData({skus: sku})
        } else {
            if (type == 'radio') {
                var tmp1 = this.data.sku.filter(item => item.value == pid),
                    tmp2 = tmp1[0].children.map(item => parseInt(item.value))
                for (let v of tmp2) {
                    var index = sku.indexOf(v)
                    if (index > -1) sku.splice(index, 1)
                }
            }
            sku.push(value)
            this.setData({skus: sku})
        }
    },
    rater(e) {
        var {type, index, field} = e.currentTarget.dataset
        if (type == 'full') {
            this.setData({[field]: index + 1})
        } else {
            this.setData({[field]: this.data[field] + index + 1})
        }
    },
    clearRater(e) {
        this.setData({[e.currentTarget.dataset.field]: 0})
    },
    datePickerShow() {
        this.setData({visible: true})
    },
    confirmSalesDate(e) {
        this.setData({sales_date: e.detail.label + ':00'})
    },
    onVisibleChange(e) {
        this.setData({visible: e.detail.visible})
    },
    changeValue(e) {
        var field = e.currentTarget.dataset.field,
            value = e.detail.value
        this.setData({[field]: value})
    },
    caogao() {
        this.setData({status: 2})
        this.submit()
    },
    shangjia() {
        this.setData({status: 1})
        this.submit()
    },
    submit() {
        var sku = this.data.sku,
            tmpSku = [],
            skus = this.data.skus,
            tmpSkus = {} //这是要传到后台的
        for (let v of sku) {
            tmpSku.push({id: v.value, child: v.children.map(item => parseInt(item.value))})
        }
        for (let v of skus) {
            for (let v2 of tmpSku) {
                if (v2.child.indexOf(v) > -1) {
                    if (!tmpSkus[v2.id]) {
                        tmpSkus[v2.id] = [v]
                    } else {
                        tmpSkus[v2.id].push(v)
                    }
                }
            }
        }
        var good = {
                id: this.data.id,
                name: this.data.name,
                type: this.data.type,
                is_new: this.data.is_new,
                brand_id: this.data.brand_id,
                scrbing_price: this.data.scrbing_price,
                discount_price: this.data.discount_price,
                // price:this.data.price,//这个字段还没用
                // delivery:this.data.delivery, //这个字段不用了
                is_presell: this.data.is_presell,
                sales_date: this.data.sales_date,
                free_freight: this.data.free_freight,
                freight: this.data.freight,
                material: this.data.material,
                status: this.data.status,
                // state:this.data.state,
                img: this.data.img,
                content: this.data.content,
                skus: this.data.skus,
                buy_info: this.data.buy_info,
                old:this.data.old,
                previous_box:this.data.previous_box,
                clue_card: this.data.clue_card,
                play_status: this.data.play_status
            },
            attr = {
                male: this.data.male,
                female: this.data.female,
                // gender_restrict:this.data.gender_restrict, //限制男女字段不用
                cross_dressing: this.data.cross_dressing,
                words_num: this.data.words_num,
                duration: this.data.duration,
                host_difficulty: this.data.host_difficulty,
                deduction_difficulty: this.data.deduction_difficulty,
                prop: this.data.prop
            },
            banner = this.data.bannerList
        wx.showModal({
            title: "提示",
            content: "是否确认提交？",
            success: (a) => {
                if (a.confirm) {
                    wx.showLoading()
                    request({
                        url: "/miniprogram/good/editGood",
                        data: {good, sku: tmpSkus, attr, banner},
                        type: 'post'
                    }).then(res => {
                        wx.hideLoading()
                        config.toast(res.msg, res.code, () => {
                            if (res.code == 200) {
                                setTimeout(() => {
                                    wx.navigateBack({delta: 1})
                                }, 1500)
                            }
                        })
                    })
                }
            }
        })



    },
    getData() {
        request({url: '/miniprogram/good/editGood', data: {id: this.data.id}}).then(res => {
            var {type, is_new} = res.data
            if (is_new == 2) {
                this.setData({title: this.data.title + '闲置'})
            }
            var txt = ''
            switch (type) {
                case 1:
                    txt = '盒装'
                    break;
                case 2:
                    txt = '城市独家'
                    break;
                case 3:
                    txt = '城市限定'
                    break;
                case 4:
                    txt = '桌游'
                    break;
                case 5:
                    txt = '周边'
                    break;
            }
            this.setData({
                title: this.data.title + txt,
                name: res.data.name,
                img: res.data.img,
                brand_id: res.data.brand_id,
                type: res.data.type,
                is_new: res.data.is_new,
                scrbing_price: res.data.scrbing_price,
                discount_price: res.data.discount_price,
                delivery: res.data.delivery,
                free_freight: res.data.free_freight,
                freight: res.data.freight,
                is_presell: res.data.is_presell,
                sales_date: res.data.sales_date,
                material: res.data.material,
                content: res.data.content,
                bannerList: res.data.banner.map(v => v.src),
                skus: res.data.skus,
                old: res.data.old,
                previous_box: res.data.previous_box,
                clue_card: res.data.clue_card,
                play_status: res.data.play_status,
                male: res.data.attribute.male,
                female: res.data.attribute.female,
                cross_dressing: res.data.attribute.cross_dressing,
                words_num: res.data.attribute.words_num,
                duration: res.data.attribute.duration,
                host_difficulty: res.data.attribute.host_difficulty,
                deduction_difficulty: res.data.attribute.deduction_difficulty,
                prop: res.data.attribute.prop,
                buy_info: res.data.buy_info,
                status: res.data.status,
            })

        })
    }
})